<template>
  <div class="dy-main AccountAddCard">
    <div class="dy-header">
      <x-header title="添加卡片" :left-options="{preventGoBack:true}" @on-click-back="back"></x-header>
    </div>
    <div class="dy-body">
      <div class="hard-card">
        <!-- <img class="card-bg" src="../../../static/img/card-bg-yellow.png" /> -->
        <i class="card-bg" :class="{typea: cardKind==='0', typeb: cardKind==='2',}"></i>
        <div class="text">
          <div class="hd">
            <img src="../../../static/icon/dy-logo.svg" />
            <span>{{ cardName }}</span>
          </div>
          <div class="md">
            <h3>{{cardNoShow}}</h3>
          </div>
          <div class="bd">
            <h4>{{ cardOwner }}</h4>
            <div class="valid-from">
              <b>VALID FROM</b>
              <em>{{validDate}}</em>
            </div>
          </div>
        </div>
      </div>
      <group gutter="0">
        <x-input title="持卡人姓名" placeholder="请输入持卡人姓名" v-model="formVal.cardHolder.val" label-width="2.05rem" class="cell"></x-input>
        <cell title="证件类型" class="cell slot-bright" is-link :value="idTypeName" value-align="left" @click.native="selectIDType"></cell>
        <x-input title="证件号码" placeholder="请输入证件号码" label-width="2.05rem" class="cell" v-model="formVal.idNo.val">
          <div class="img-camera-wrap" slot="right">
            <img @click="scanIdCard()" class="imgCamera" src="../../../static/icon/camera.svg" />
          </div>
        </x-input>
        <x-input v-if="cardKind === '0'" title="有效期" placeholder="请输入有效期(例1903)" label-width="2.05rem" class="cell" v-model="creditForm.validFrom.val">
          <div class="img-camera-wrap" slot="right">
            <img @click="showMsg()" class="imgCamera" src="../../../static/icon/question.svg" />
          </div>
        </x-input>
        <x-input v-if="cardKind === '1'" title="取款密码" placeholder="请输入取款密码" label-width="2.05rem" v-model="payPwd" class="cell" @click.native="showPayKeyboard(0)"></x-input>
        <x-input v-if="cardKind === '0'" title="查询密码" placeholder="请输入查询密码" label-width="2.05rem" v-model="creditForm.selectPwd.val" class="cell" @click.native="showPayKeyboard(1)"></x-input>
        <zx-smscode v-if="cardKind !== '2'" :sendObj="smsSendObj1" @send-mobile="getSmsMobile" :codeTypeVal="yanzCode" :isDisabled="LDTdisable" class="smscode" v-model="formcardVal.smsCode.val" type="text" title="验证码"></zx-smscode>
        <!-- 两地一本通 -->
        <cell v-if="cardKind === '2'" title="激活码发送至" class="cell slot-bright" is-link :value="LDTcodeType" value-align="left" @click.native="selectLDType"></cell>
        <x-input v-if="LDTcodeType === '手机'" title="手机号码" placeholder="请输入手机号码" label-width="2.05rem" v-model="LDTForm.LDTcodeTypeVal.val" class="cell" @on-blur="regText('phoneNumber', LDTForm.LDTcodeTypeVal.val)"></x-input>
        <x-input v-if="LDTcodeType === '邮箱'" title="邮箱" placeholder="请输入邮箱" label-width="2.05rem" v-model="LDTForm.LDTcodeTypeVal.val" class="cell" @on-change="regText('email', LDTForm.LDTcodeTypeVal.val)"></x-input>
        <zx-smscode v-if="cardKind === '2'" :sendObj="smsSendObj2" @send-mobile="getSmsMobile" :codeTypeVal="yanzCode" :isDisabled="LDTdisable" class="smscode" v-model="LDTForm.smsCode.val" type="text" title="激活码"></zx-smscode>
        <!-- 两地一本通 -->
      </group>
      <actionsheet v-model="creSwitch" :menus="menus" @on-click-menu="click" ></actionsheet>
      <actionsheet v-model="LDTSwitch" :menus="menusLDT" @on-click-menu="clickLDT" ></actionsheet>
      <toast v-model="showPositionValue" type="text" width="6rem" :time="800" is-show-mask :text="errormsg" position="middle">{{ errormsg }}</toast>
      <!--<p>{{ppp}}</p>-->
      <div class="confirm">
        <x-button :disabled="allowClick" action-type="button" @click.native="addcheck(formVal)">确认添加</x-button>
      </div>
    </div>
    <!--<div class="dy-footer"></div>-->
    <zx-dialog v-model="tipsShow" type="tips" title="有效期说明" butType="button" :data="['确认']" @on-click-yes="clickYes">
      <div slot="body" class="creditTips">
        <img src="../../../static/img/creditForm.png" />
        <p class="txt">有效期是打印在信用卡正面卡号下方，标准格式为月份在前，年份在后的一串数字</p>
      </div>
    </zx-dialog>
  </div>
</template>
<script>
export default{
  data () {
    return {
      // ppp: '暂无',
      // cardKindtest: 'true', // 测试用字段
      tipsShow: false, // 信用卡有效期说明
      cardKind: '', // 0 信用卡 1 借记卡 2 两地一本通
      cardName: '', // 卡片名称
      cardOwner: 'Wu Yiming', // 卡片所有者英文
      validDate: '', // 有效期
      cardNo: '', // 真实卡号
      cardNoShow: '8888 **** **** 8888', // 展示卡号
      idType: '1',
      idTypeName: '身份证',
      idNo: '', // 证件号码
      creSwitch: false,
      LDTSwitch: false, // 选择两地一本通激活码获取途径 弹窗控制
      codeText: '发送验证码', // 验证按钮显示内容
      codeTime: 10, // 验证码倒计时
      isTime: null, // 验证码状态
      disableCode: false,
      LDTcodeType: '', // 两地一本通激活码获取途径  0 手机， 1，邮箱
      menusLDT: {
        menu1: '手机',
        menu2: '邮箱'
      }, // 两地一本通 激活码获取途径
      LDTdisable: 'true', // 是否可以获取激活码
      LDTcode: '', // 两地一本通激活码
      yanzCode: '', // 验证码发送的 手机 或者 邮箱
      menus: {
        menu1: '身份证',
        menu2: '军官证',
        menu3: '港澳台证',
        menu4: '护照',
        menu5: '临时身份证'
      },
      payPwd: '', // 取款密码
      payPwdRel: '', // 取款密码发送
      formVal: {
        cardHolder: {val: '', type: [{typeName: 'minLen', typeVal: '2', msg: '请输入正确的姓名'}]}, // 持卡人姓名
        idNo: {val: '', type: [{typeName: 'maxLen', typeVal: '24', msg: '请输入正确的证件号码'}]} // 证件号码
      },
      formcardVal: {
        smsCode: {val: '', type: [{typeName: 'minLen', typeVal: '6', msg: '验证码错误'}]} // 短信验证码
      },
      // 信用卡使用的字段
      creditForm: {
        validFrom: {val: '', type: [{typeName: 'minLen', typeVal: '1', msg: '有效期不能为空'}]},
        selectPwd: {val: '', type: [{typeName: 'minLen', typeVal: '1', msg: '查询密码不能为空'}]}
      },
      LDTForm: {
        LDTcodeTypeVal: {val: '', type: [{typeName: 'minLen', typeVal: '1', msg: '号码不能为空'}]},
        smsCode: {val: '', type: [{typeName: 'minLen', typeVal: '6', msg: '激活码错误'}]}
      },
      errormsg: '', // 错误提示
      showPositionValue: false, // 提示开关
      smsSendObj1: {
        'bussType': '15',
        'sendFlag': '2',
        'clientNo': this.$store.getters.getClientNo,
        'mobile': '',
        'cardNo': ''
      },
      smsSendObj2: {
        'bussType': '15',
        'sendFlag': '1',
        'clientNo': '',
        'mobile': this.LDTForm.LDTcodeTypeVal.val,
        'cardNo': ''
      },
      smsMobile: '' // 验证码接口返回的手机号
    }
  },
  computed: {
    allowClick () {
      if (this.cardKind === '1') {
        return this.formVal.cardHolder.val === '' || this.formVal.idNo.val === '' || this.formcardVal.smsCode.val === '' || this.payPwd === ''
      }
      if (this.cardKind === '0') {
        return this.formVal.cardHolder.val === '' || this.formVal.idNo.val === '' || this.creditForm.validFrom.val === '' || this.creditForm.selectPwd.val === '' || this.formcardVal.smsCode.val === ''
      }
      if (this.cardKind === '2') {
        return this.formVal.cardHolder.val === '' || this.formVal.idNo.val === '' || this.LDTcodeType === '' || this.LDTForm.LDTcodeTypeVal.val === '' || this.LDTForm.smsCode.val === ''
      }
      return false
    }
  },
  methods: {
    back () {
      this.$publicFun.goBack(this)
    },
    init () {
      // 初始化数据
      let lData = this.$route.query
      if (lData.cardNo) {
        this.cardNo = lData.cardNo
        this.cardNoShow = this.protectAccountNo(lData.cardNo)
      }
      if (lData.cardKind) {
        this.cardKind = lData.cardKind
        if (lData.cardKind === '2') {
          this.LDTcodeType = '手机'
          this.LDTdisable = 'false'
        }
      }
      // this.cardKind = (Math.floor((Math.random() * 100)) % 3).toString() // 此处随机值
      if (lData.cardName) {
        this.cardName = lData.cardName
      }
    },
    selectIDType () {
      this.creSwitch = !this.creSwitch
    },
    selectLDType () {
      this.LDTSwitch = !this.LDTSwitch
    },
    click (key, item) {
      if (item === '身份证') {
        this.idType = '1'
        this.idTypeName = item
      } else if (item === '港澳台证') {
        this.idType = 'X5'
        this.idTypeName = item
      }
    },
    clickLDT (key, item) {
      if (item === '邮箱') {
        this.$bridge.callhandler('showErrorHUD', {
          'type': 'toast',
          'errorMess': '抱歉，邮箱验证功能正在开发之中'
        })
      } else {
        this.LDTcodeType = item
      }
    },
    /**
     * 类型：辅助
     *验证输入合法性
     *@param {string} module 验证对象
     *
     **/
    addcheck (module) {
      for (let key in module) {
        let lObj = module[key]
        let lRes = this.$publicFun.formCheck(lObj)
        if (!lRes.isOK) {
          this.errormsg = lRes.msg
          this.showPositionValue = true
          return false
        }
      }
      if (this.cardKind === '0' || this.cardKind === '1') {
        for (let key in this.formcardVal) {
          let lObj = this.formcardVal[key]
          let lRes = this.$publicFun.formCheck(lObj)
          if (!lRes.isOK) {
            this.errormsg = lRes.msg
            this.showPositionValue = true
            return false
          }
        }
      } else if (this.cardKind === '0') {
        for (let key in this.creditForm) {
          let lObj = this.creditForm[key]
          let lRes = this.$publicFun.formCheck(lObj)
          if (!lRes.isOK) {
            this.errormsg = lRes.msg
            this.showPositionValue = true
            return false
          }
        }
      } else if (this.cardKind === '2') {
        // 这里有个特殊情况要处理一下
        if (this.LDTcodeType === '手机') {
          this.LDTForm.LDTcodeTypeVal.type = [{typeName: 'minLen', typeVal: '1', msg: '号码不能为空'}, {typeName: 'phoneNumber', typeVal: '', msg: '号码格式不对'}]
        } else {
          this.LDTForm.LDTcodeTypeVal.type = [{typeName: 'minLen', typeVal: '1', msg: '号码不能为空'}, {typeName: 'email', typeVal: '', msg: '号码格式不对'}]
        }
        for (let key in this.LDTForm) {
          let lObj = this.LDTForm[key]
          let lRes = this.$publicFun.formCheck(lObj)
          if (!lRes.isOK) {
            this.errormsg = lRes.msg
            this.showPositionValue = true
            return false
          }
        }
      }
      this.checkSmsCode() // 验证成功之后的动作
    },
    /*
    *  类型：接口
    *  验证码校验接口
    */
    checkSmsCode () {
      if (this.smsMobile) {
        let obj = {
          'bussType': '15',
          'mobile': this.smsMobile,
          'smsCode': this.formcardVal.smsCode.val || this.LDTForm.smsCode.val
        }
        this.$bridge.callhandler('nativeRequest',
          JSON.stringify({
            'requstSource': 'internetRequest',
            'url': 'mstep.do?act=business',
            'params': {'method_Name': 'checkCode', 'basic_Data': JSON.stringify(obj)}
          }),
          (response) => {
            console.log(JSON.stringify(obj))
            let respData = JSON.parse(response).data
            console.log(respData)
            if (respData.head.respCode === '000000') { // 返回000000为正常，否则输出错误
              this.goNext()
            } else { // 调用原生提示，输出错误内容
              this.$bridge.callhandler('showErrorHUD', {
                'type': 'toast',
                'errorMess': respData.head.respMsg
              })
            }
          })
      } else {
        this.errormsg = '请获取验证码或激活码'
        this.showPositionValue = true
        return false
      }
    },
    /*
    *  类型：接口
    *  加挂卡片
    */
    goNext () {
      let lLDTcodeType = this.LDTcodeType === '手机' ? '0' : '1'
      let obj = {
        'clientNo': this.$store.getters.getClientNo,
        'cardNo': this.cardNo,
        'cardHolder': this.formVal.cardHolder.val,
        'idType': this.idType,
        'idNo': this.formVal.idNo.val,
        'payPwd': '111111',
        'smsCode': this.formcardVal.smsCode.val,
        'validity': this.creditForm.selectPwd.val,
        'activationMethod': lLDTcodeType,
        'mobile': this.LDTForm.LDTcodeTypeVal.val,
        'email': this.LDTForm.LDTcodeTypeVal.val,
        'activationCode': this.LDTForm.smsCode.val
      }
      this.$bridge.callhandler('nativeRequest',
        // JSON.stringify({
        //   'requstSource': 'internetRequest',
        //   'url': 'mstep.do?act=business',
        //   'params': {'method_Name': 'addCard',
        //     'basic_Data': JSON.stringify({
        //       'clientNo': 'E18052500000012',
        //       'cardNo': '6229331700000037766',
        //       'cardHolder': '詹客户00122732的中文全',
        //       'idType': '001',
        //       'idNo': '117001028310100',
        //       'payPwd': '111111',
        //       'smsCode': '111111',
        //       'validity': '',
        //       'activationMethod': '',
        //       'mobile': '15910086238',
        //       'email': '',
        //       'activationCode': ''
        //     })}
        // }),
        JSON.stringify({
          'requstSource': 'internetRequest',
          'url': 'mstep.do?act=business',
          'params': {'method_Name': 'addCard', 'basic_Data': JSON.stringify(obj)}
        }),
        (response) => {
          console.log(JSON.stringify(obj))
          let respData = JSON.parse(response).data
          console.log(respData)
          if (respData.head.respCode === '000000') { // 返回000000为正常，否则输出错误
            this.$router.push({name: 'AccountAddCardResult'})
          } else { // 调用原生提示，输出错误内容
            this.$bridge.callhandler('showErrorHUD', {
              'type': 'toast',
              'errorMess': respData.head.respMsg
            })
          }
        })
    },
    /*
    *  类型：辅助
    *  扫描身份证
    */
    scanIdCard () {
      let _this = this
      this.$bridge.callhandler('scanIdCard', null,
        function (response) {
          let data = JSON.parse(response)
          console.log(data)
          if (data.status === 0 || data.status === '0') {
            let returnData = data.result
            _this.formVal.cardHolder.val = returnData.name
            _this.formVal.idNo.val = returnData.id
          } else {
            console.log('fail')
          }
        })
    },
    /*
    *  类型：辅助
    *  调用安全键盘
    */
    showPayKeyboard () {
      document.activeElement.blur()
      let _this = this
      this.$bridge.callhandler('showPayKeyboard', null,
        function (response) {
          let data = JSON.parse(response)
          if (_this.cardKind === '0') {
            _this.creditForm.selectPwd.val = '******'
            _this.padPwdRel = data.cipher
          } else if (_this.cardKind === '1') {
            _this.payPwd = '******'
            _this.padPwdRel = data.cipher
          }
        })
    },
    /**
     * 账号保护，脱敏处理
     * @param {Object} accountNo 传入格式为连续数字的一串卡号
     * @return xxxx **** **** xxxx (格式："4063 **** **** 1099")
     */
    protectAccountNo (accountNo) {
      let number = accountNo.replace(/\s/g, '') // 去除空格
      let length = number.length
      let str1 = number.substring(0, 4)
      let str2 = ' **** **** '
      let str3 = number.substring(length - 4, length)
      return str1 + str2 + str3
    },
    showMsg () {
      this.tipsShow = true
    },
    clickYes (val) {
      this.tipsShow = false
    },
    regText (type, val) {
      if (!this.$publicFun.strIsEmptyOrNull(val)) {
        let lStr = this.$publicFun.stringFilter(val, type)
        if (lStr.isOK) {
          this.yanzCode = val
        }
      }
    },
    getSmsMobile (val) {
      this.smsMobile = val
    }
  },
  mounted () {
    this.init()
    // console.log(this.$store.getters.getClientNo)
  }
}
</script>
<style lang="less">
  .AccountAddCard {
    .dy-body {
      background-color: #fff;
      overflow: auto;
      .hard-card {
        position: relative;
        margin: .46rem auto .58rem;
        width: 6.28rem;
        height: 3.68rem;
        i.card-bg {
          display: block;
          width: 100%;
          height: 100%;
          background: url(../../../static/img/card-bg-yellow.png) no-repeat center center;
          background-size: 100%;
        }
        i.card-bg.typea {
          background: url(../../../static/img/card-bg-blue.png) no-repeat center center;
          background-size: 100%;
        }
        i.card-bg.typeb {
          background: url(../../../static/img/card-bg-red.png) no-repeat center center;
          background-size: 100%;
        }
        .text {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          color: #845814;
          .hd {
            display: flex;
            align-items: flex-end;
            padding: .4rem .38rem .5rem;
            overflow: hidden;
            img {
              width: 1.78rem;
              height: .36rem;
            }
            span {
              flex: 1;
              margin-left: .18rem;
            }
          }
          .md {
            padding: 0 .46rem;
            h3 {
              font-size: .44rem;
              line-height: .58rem;
            }
          }
          .bd {
            padding: .02rem .46rem 0;
            h4 {
              line-height: .58rem;
            }
            .valid-from {
              margin-top: .12rem;
              b {
                display: inline-block;
                width: .73rem;
                font-size: .18rem;
                line-height: .2rem;
                font-weight: bold;
              }
              em {
                font-size: .3rem;
                line-height: .36rem;
              }
            }
          }
        }
      }
      .confirm {
        margin: .8rem auto .62rem;
        padding: 0 .4rem;
        width: 100%;
      }
      .slot-bright {
        .vux-cell-bd {
          width: 2.05rem;
        }
        .weui-cell__ft:after {
          transform:rotate(135deg);
        }
      }
      .img-camera-wrap {
        display: inline-block;
        width:.48rem;
        height: .38rem;
        vertical-align: middle;
      }
      .smscode {
        position: relative;
        &:before {
          content: " ";
          position: absolute;
          left: 15px;
          top: 0;
          right: 0;
          border-top: 1px solid #D9D9D9;
          color: #D9D9D9;
          -webkit-transform-origin: 0 0;
          transform-origin: 0 0;
          -webkit-transform: scaleY(0.5);
          transform: scaleY(0.5);
        }
      }
    }
    .creditTips {
      img {
        width: 100%;
      }
      .txt {
        font-size: 0.24rem;
        color: #9B9B9B;
        line-height:0.34rem;
      }
    }
  }
</style>
